<template>
  <div class="p-2">
    <!-- 添加或修改宿舍楼-楼层对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="buildingFloorFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="楼层名称" prop="name">
          <!-- <el-input v-model="form.name" placeholder="请输入楼层名称" /> -->
          <el-select v-model="form.name" placeholder="请选择楼层名称" style="width:100%" filterable>
            <el-option v-for="text in floors" :key="text" :label="text" :value="text">{{ text }}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联摄像头" prop="devices">
          <!-- <el-input v-model="form.devices" type="textarea" placeholder="请输入内容" /> -->
          <el-select v-model="form.devices" placeholder="请选择关联摄像头" multiple style="width:100%" filterable>
            <el-option v-for="dict in sxtDeviceList" :key="dict.id" :label="dict.name" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="负责人" prop="workers">
          <!-- <el-select v-model="form.workers" placeholder="请选择负责人" multiple style="width:100%" filterable>
            <el-option
              v-for="dict in sxtDeviceList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
              >{{ dict.name+' （'+dict.location+'）' }}</el-option
            >
          </el-select> -->
          <staff-select v-model="form.workers" multiple :style="{width:'100%'}"></staff-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BuildingFloor" lang="ts">
import { listBuildingFloor, getBuildingFloor, delBuildingFloor, addBuildingFloor, updateBuildingFloor } from '@/api/dormitory/buildingFloor';
import { BuildingFloorVO, BuildingFloorQuery, BuildingFloorForm } from '@/api/dormitory/buildingFloor/types';
const props = defineProps({
  nodeId: String || Number || undefined,
  buildingId: String || Number || undefined
});
const emit = defineEmits(['onSuccess']);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const buildingFloorList = ref<BuildingFloorVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const floors = ref<Array<string>>([]);

const queryFormRef = ref<ElFormInstance>();
const buildingFloorFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: BuildingFloorForm = {
  id: undefined,
  nodeId: undefined,
  name: undefined,
  buildingId: undefined,
  orderNum: undefined,
  devices: undefined,
  deviceText: undefined,
  workers: undefined,
  workerText: undefined,
  roomCount: undefined,
  roomMemberCount: undefined,
  remark: undefined,
  status: undefined
};
const data = reactive<PageData<BuildingFloorForm, BuildingFloorQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    nodeId: undefined,
    name: undefined,
    buildingId: undefined,
    orderNum: undefined,
    devices: undefined,
    deviceText: undefined,
    workers: undefined,
    workerText: undefined,
    roomCount: undefined,
    roomMemberCount: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: 'ID不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '楼层名称不能为空', trigger: 'blur' }],
    devices: [{ required: true, message: '关联摄像头不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询宿舍楼-楼层列表 */
const getList = async () => {
  loading.value = true;
  const res = await listBuildingFloor(queryParams.value);
  buildingFloorList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  buildingFloorFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: BuildingFloorVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加宿舍楼-楼层';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: any) => {
  reset();
  const _id = row?.sourceId || ids.value[0];
  const res = await getBuildingFloor(_id);
  res.data['devices'] = res.data.devices ? res.data.devices?.split(',') : [];
  res.data['workers'] = res.data.workers ? res.data.workers?.split(',') : [];
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改宿舍楼-楼层';
};

/** 提交按钮 */
const submitForm = () => {
  buildingFloorFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      let params = {
        ...form.value,
        devices: form.value.devices?.join(','),
        workers: form.value.workers?.join(',')
      };
      let tipText = '修改成功';
      if (form.value.id) {
        await updateBuildingFloor(params).finally(() => (buttonLoading.value = false));
      } else {
        tipText = '新增成功';
        params['nodeId'] = props.nodeId;
        params['buildingId'] = props.buildingId;
        await addBuildingFloor(params).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess(tipText);
      dialog.visible = false;
      emit('onSuccess');
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: any) => {
  const _ids = row?.sourceId || ids.value;
  await proxy?.$modal.confirm('是否确认删除"' + row?.name + '"？').finally(() => (loading.value = false));
  await delBuildingFloor(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  emit('onSuccess');
};

import { DeviceInfoQuery, DeviceInfoVO } from '@/api/device/deviceInfo/types';
import { listDeviceInfo } from '@/api/device/deviceInfo';
const deviceQueryParams = reactive<DeviceInfoQuery>({
  pageNum: 1,
  pageSize: 10000,
  parentId: undefined,
  type: 3,
  name: undefined,
  series: undefined,
  ip: undefined,
  deviceCode: undefined,
  guid: undefined,
  area: undefined,
  location: undefined,
  position: undefined,
  onlineStatus: undefined,
  offlineTime: undefined,
  status: 1
});
const sxtDeviceList = ref<any>([]);
const getDeviceInfoList = async (type: number) => {
  deviceQueryParams.type = type;
  const res = await listDeviceInfo(deviceQueryParams);
  return res.rows;
};

defineExpose({
  handleAdd,
  handleUpdate,
  handleDelete
});

onMounted(() => {
  for (let i = 1; i < 51; i++) {
    floors.value.push(`${i}层`);
  }
  getDeviceInfoList('1,4').then((res) => {
    sxtDeviceList.value = res;
  });
});
</script>
